import LogUtil from './logUtil'
import V2NIMLoginServiceImpl from './V2NIMLoginServiceImpl'

type V2NIMInitialOptions = {
  appkey: string
  debugLevel: number
}

type V2NIMService = {
  pluginName: string
  core: NIM
}

const serviceMap = new Map<string, V2NIMService>()

// NIM 核心类, 核心类提供插拔式的注入对应业务模块来实现对应的能力.
// 核心类自身应该少挂功能
export class NIM {
  private static instance: NIM | undefined
  V2NIMLoginService: V2NIMLoginServiceImpl
  logUtil: LogUtil

  constructor(options: V2NIMInitialOptions) {
    // 工具模块初始化
    this.logUtil = new LogUtil(options.debugLevel)

    // 业务模块初始化
    this.V2NIMLoginService = new V2NIMLoginServiceImpl(this)
    this.logUtil.log('NIM initialized')

    serviceMap.forEach((service, key) => {
      // @ts-ignore
      this[key] = new service(this)
    })

    NIM.instance = this
  }

  // 单例
  static getInstance(options: V2NIMInitialOptions) {
    if (NIM.instance) {
      return NIM.instance
    } else {
      NIM.instance = new NIM(options)
      return NIM.instance
    }
  }

  static usePlugin(plugin: V2NIMService) {
    serviceMap.set(plugin.pluginName, plugin)
  }

  // 反初始化.. 其实只是简单销毁内存数据
  destroy() {
    this.V2NIMLoginService.destroy()
    NIM.instance = undefined
  }
}
